// pages/add-transfer/add-transfer.js
import tips from '../../lib/tips';
var util = require('../../utils/util.js');
const app = getApp();
var QQMapWX = require('../../lib/qqmap-wx-jssdk.min.js');
var qqmapsdk;

Array.prototype.remove = function(obj) {
  for (var i = 0; i < this.length; i++) {
    var temp = this[i];
    if (!isNaN(obj)) {
      temp = i;
    }
    if (temp == obj) {
      for (var j = i; j < this.length; j++) {
        this[j] = this[j + 1];
      }
      this.length = this.length - 1;
    }
  }
};
Page({
  /**
   * 页面的初始数据
   */
  data: {
    baseDomain: app.globalData.baseDomain,
    start_camera_display: "none",
    image_list_display: "flex",
    title: "",
    content: "",
    price: 0.0,
    postage: "",
    postageHide: true,
    newOrOld: "请选择",
    newOrOldList: ['全新', '九成新', '八成新', '七成新', '六成新', '五成新'],
    province: "",
    adcode: "",
    city: "",
    district: "",
    uploadImageList: null,
    tipsData: {
      title: '',
      isHidden: true
    },
    transfer: null,
    btnName: "立即发布",
    transferId: null,
    area: "点击获取位置"
  },
  getLocation: function() {
    var that = this;
    qqmapsdk = new QQMapWX({
      key: 'UELBZ-QQUW3-CXD3L-3G3Q6-NPENQ-TYB5T' // 必填
    });
    var city = that.data.city;
    if (!city || city.length == 0) {
      wx.chooseLocation({
        success: function(res) {
          qqmapsdk.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude
            },
            success: function(addressRes) {
              that.setData({
                province: addressRes.result.ad_info.province,
                city: addressRes.result.ad_info.city,
                district: addressRes.result.ad_info.district,
                adcode: addressRes.result.ad_info.adcode,
                area: addressRes.result.ad_info.city + "|" + addressRes.result.ad_info.district
              });
            },
            fail: function(res) {},
            complete: function(res) {}
          })
        },
      })
    }

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    var transferId = options.transferId;
    qqmapsdk = new QQMapWX({
      key: 'UELBZ-QQUW3-CXD3L-3G3Q6-NPENQ-TYB5T' // 必填
    });
    wx.getLocation({
      success: function(res) {
        qqmapsdk.reverseGeocoder({
          location: {
            latitude: res.latitude,
            longitude: res.longitude
          },
          success: function(addressRes) {
            that.setData({
              province: addressRes.result.ad_info.province,
              city: addressRes.result.ad_info.city,
              district: addressRes.result.ad_info.district,
              adcode: addressRes.result.ad_info.adcode,
              area: addressRes.result.ad_info.city + "|" + addressRes.result.ad_info.district
            });
          },
          fail: function(res) {},
          complete: function(res) {}
        })
      },
    })
    if (transferId) {
      wx.request({
        url: app.globalData.apiDomain + '/api/transfer/getTransferDetail/' + transferId,
        success(res) {
          var obj = JSON.parse(res.data.data.contentImg);
          var postageHide = false;
          var postage = res.data.data.postage;
          if (res.data.data.noPostage == 1) {
            postageHide = true;
            postage = "";
          }
          that.setData({
            transfer: res.data.data,
            uploadImageList: obj,
            transferId: transferId,
            postageHide: postageHide,
            newOrOld: res.data.data.newOld,
            btnName: "确认编辑",
            postage: postage
          });
        }
      })
    } else {

    }



    // try {
    //   var value = wx.getStorageSync('uploadImageList')
    //   if (value) {
    //     that.setData({
    //       start_camera_display: "none",
    //       image_list_display: "flex"
    //     });
    //   } else {
    //     that.setData({
    //       start_camera_display: "flex",
    //       image_list_display: "none"
    //     });
    //   }
    // } catch (e) {
    //   // Do something when catch error
    // }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  openAlbum: function(e) {
    //console.log(11111);
    // this.setData({
    //   image_list_display: "flex",
    //   start_camera_display: "none"
    // });
  },

  showToast(title, duartion) {
    const that = this;
    const tipsData = {
      title: title || '',
      duartion: duartion || 2000,
      isHidden: false
    };
    tips.toast(that.data.tipsData);
    that.setData({
      tipsData
    });
    setTimeout(() => {
      tipsData.isHidden = true;
      that.setData({
        tipsData
      });
    }, tipsData.duartion);
  },

  //监听标题输入
  listenerTitleInput(e) {
    this.data.title = e.detail.value;
  },
  //监听描述输入
  listenerContentInput(e) {
    this.data.content = e.detail.value;
  },
  //监听价格输入
  listenerPriceInput(e) {
    this.data.price = e.detail.value;
  },
  //监听邮费输入
  listenerPostageInput(e) {
    this.data.postage = e.detail.value;
  },
  formSubmit: util.throttle(function(e) {
    const that = this;
    var title = null;
    var content = null;
    var price = null;
    var postage = null;
    var city = this.data.city;
    if (this.data.newOrOld == "请选择") {
      that.showToast('请选择新旧程度');
      return;
    }
    if (!city || city.length == 0) {
      that.showToast('请点击获取位置，或更改手机设置允许获取地理位置');
      return;
    }
    if (this.data.title) {
      title = this.data.title;
    } else {
      title = e.detail.value.title;
    }

    if (this.data.content) {
      content = this.data.content;
    } else {
      content = e.detail.value.content;
    }

    if (this.data.price) {
      price = this.data.price;
    } else {
      price = e.detail.value.price;
    }

    if (this.data.postage) {
      postage = this.data.postage;
    } else {
      postage = e.detail.value.postage;
    }
    if (!title) {
      that.showToast('名称不能为空');
      return;
    }
    if (title.length > 30) {
      that.showToast('名称不能大于30个字符');
      return;
    }
    if (title.length < 5) {
      that.showToast('名称不能小于5个字符');
      return;
    }

    if (!content) {
      that.showToast('描述不能为空');
      return;
    }

    if (content.length > 200) {
      that.showToast('描述不能大于200个字符');
      return;
    }
    if (!price) {
      that.showToast('转让价格不能为空');
      return;
    }

    if (/^\d+$/.test(price) || /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(price)) {} else {
      that.showToast('转让价格输入有误');
      return;
    }

    if (this.data.uploadImageList == null || this.data.uploadImageList.length == 0) {
      that.showToast('至少要上传一张照片');
      return;
    }

    //如果不包邮情况下校验邮费
    if (!this.data.postageHide) {
      if (!postage) {
        that.showToast('邮费不能为空');
        return;
      }
      if (/^\d+$/.test(postage) || /^(([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/.test(postage)) {} else {
        that.showToast('邮费输入有误');
        return;
      }
    }

    var transferId = that.data.transferId;
    var contentImg = that.data.uploadImageList;
    var isNew = e.detail.value.isNew;
    var noPostage = e.detail.value.noPostage;
    var province = e.detail.value.province;
    var city = e.detail.value.city;
    var district = e.detail.value.district;
    var adcode = e.detail.value.adcode;
    if (this.data.postageHide) {
      postage = 0.0;
    }
    var url = null;

    if (transferId) {
      url = app.globalData.apiDomain + '/api/transfer/updateTransfer';
    } else {
      url = app.globalData.apiDomain + '/api/transfer/createTransfer';
    }
    //调用获取商品列表接口

    wx.request({
      url: url,
      method: "POST",
      data: {
        id: transferId,
        title: title,
        content: content,
        contentImg: contentImg,
        price: price,
        newOld: this.data.newOrOld,
        noPostage: noPostage,
        postage: postage,
        province: province,
        city: city,
        district: district,
        adcode: adcode,
        openId: app.globalData.openId,
        nickName: app.globalData.userInfo.nickName,
        avatarUrl: app.globalData.userInfo.avatarUrl
      },
      success: function(res) {
        wx.redirectTo({
          url: '../myTransfer/myTransfer',
          complete: function() {
            wx.showToast({
              title: '发布成功',
              image: '../../images/correct_toast.png',
              duration: 2000,
            });
          }
        })

      },
      complete: function() {

      }
    });
  }),
  formReset: function(e) {

  },

  //是否包邮开关改变
  changePostage: function(e) {
    if (e.detail.value) {
      this.setData({
        postage: "",
        postageHide: true
      });
    } else {
      this.setData({
        postageHide: false
      });
    }
  },
  selectNewOrOld: function(e) {
    const that = this;
    wx.showActionSheet({
      itemList: that.data.newOrOldList,
      success(res) {
        that.setData({
          newOrOld: that.data.newOrOldList[res.tapIndex]
        });
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },
  //上传图片
  onUploadImage: function(e) {
    var that = this;
    //判断图片集数量，如果超过限制不让上传
    if (that.data.uploadImageList != null && that.data.uploadImageList.length == 3) {
      wx.showToast({
        title: '只能上传3张图片',
        image: '../../images/failure_toast.png',
        duration: 2000
      });
      return;
    }
    //可以上传的图片数量
    var canUploadImageCount = 3;
    if (that.data.uploadImageList) {
      canUploadImageCount = canUploadImageCount - that.data.uploadImageList.length;
    }
    //可以上传数量大于0可以上传否则给出提示
    if (canUploadImageCount > 0) {
      //调用微信上传图片
      wx.chooseImage({
        sizeType: ['compressed'],
        count: canUploadImageCount,
        sourceType: ['album'],
        success(res) {
          var imagesURL = new Array();
          if (that.data.uploadImageList) {
            imagesURL = that.data.uploadImageList;
          }
          const tempFilePaths = res.tempFilePaths;
          for (var i = 0; i < tempFilePaths.length; i++) {
            wx.uploadFile({
              url: app.globalData.apiDomain + '/upload/uploadTransferImg', //仅为示例，非真实的接口地址
              filePath: tempFilePaths[i],
              name: 'file',
              formData: {
                'user': 'test'
              },
              success(res) {
                var data = JSON.parse(res.data);
                imagesURL.push(data.data);
                //console.log(data.data);
                that.setData({
                  uploadImageList: imagesURL
                });
              }
            })
          }
        }
      });
    } else {
      wx.showToast({
        title: '您已经选择了3张图片，您可以删除其中一张再进行选择',
        image: '../../images/failure_toast.png',
        duration: 2000
      });
    }

  },

  //移除图片
  removeImage: function(e) {
    var that = this;
    var imageArray = that.data.uploadImageList;
    //console.log(e.currentTarget.dataset.imageid);
    if (imageArray.length != null) {
      imageArray.remove(e.currentTarget.dataset.imageid);
      that.setData({
        uploadImageList: imageArray
      });
    }
    //console.log(that.data.uploadImageList.length);
  }
})